﻿using System;
using System.Web.Mvc;
using Data;
using MySimpleDiary.Models;

namespace MySimpleDiary.Controllers
{
    public class AccountController : Controller
    {

        private IMembershipService MembershipService;
        private IFormsAuthenticationService FormService;

        protected override void Initialize(System.Web.Routing.RequestContext requestContext)
        {
            if (FormService == null) { FormService = new FormsAuthenticationService(); }
            if (MembershipService == null) { MembershipService = new AccountMembershipService(); }

            base.Initialize(requestContext);
        }


        public ActionResult UserLogin()
        {
            return View();
        }

        public ActionResult SignOut()
        {
            FormService.SignOut();
            return RedirectToAction("Index", "Home");
        }

        [HttpPost]
        public ActionResult UserLogin(SiteUserModels.SiteUserLoginModel model)
        {
            try
            {
                if (MembershipService.ValidateUser(model.username, model.password))
                {
                    FormService.SignIn(model.username, model.remeber_me);
                    SiteUserModels.SiteUserModel user = SiteUserRepository.LoadLoggedInUserDetails(model.username);
                    Session.Add("current_firstname", user.firstname);
                    Session.Add("current_userid", user.user_id);
                }
                return RedirectToAction("Index", "Home");
            }
            catch (ArgumentException e)
            {
                ViewData["ErrorMessage"] = e.Message;
                return RedirectToAction("Index", "Home");
            }
        }

        public ActionResult UserRegistration()
        {
            SelectList list = new SelectList(SiteUserRepository.GetTimezones(), "timezone_id", "location");
            ViewData["timezones"] = list;
            return View();
        }

        [HttpPost]
        public ActionResult UserRegistration(SiteUserModels.SiteUserRegistrationModel model)
        {
            if (ModelState.IsValid)
            {
                SiteUserRepository.CreateUser(model.username, model.email, model.password, model.firstname, model.firstname, model.timezone_id);
                return RedirectToAction("Index", "Home");
            }
            
            return UserRegistration();
        }
    }
}
